// request.js
import {
  BASE_URL
} from '../constant/index.js'

const request = (url, method, data = {}, options = {}) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${BASE_URL}${url}`, // 拼接基础地址和接口路径
      method: method, // 请求方法
      data: data, // 请求参数
      header: {
        'Content-Type': 'application/json',
        ...(options.headers || {}), // 支持自定义 headers
        Authorization: wx.getStorageSync('token') || '', // Token 鉴权
      },
      timeout: options.timeout || 10000, // 请求超时时间
      success: (res) => {
        // 响应拦截处理
        // if (res.statusCode === 200) {
        //   resolve(res.data); // 正常返回数据
        // } else {
        //   wx.showToast({
        //     title: res.data.message || '请求失败',
        //     icon: 'none',
        //   });
        //   reject(res.data);
        // }
        resolve(res.data)
      },
      fail: (err) => {
        wx.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none',
        });
        reject(err);
      },
    });
  });
};

// 导出常用的请求方法
const get = (url, data = {}, options = {}) => request(url, 'GET', data, options);
const post = (url, data = {}, options = {}) => request(url, 'POST', data, options);
const put = (url, data = {}, options = {}) => request(url, 'PUT', data, options);
const del = (url, data = {}, options = {}) => request(url, 'DELETE', data, options);

export default {
  get,
  post,
  put,
  del,
};